const { question } = require('./question');
const { exec } = require('child_process');
const path = require('path')
const fs = require('fs')
const c = require('colors')

const componentDir = '../src/components'

const commonComponentDir = '../src/components/common/'

// var middlelizeKey = function (str) {
//   return str.replace(/\B([A-Z])/g, '-$1').toLowerCase()
// };

async function main() {
  const componentName = await question(
    '请输入组件名称\n' +
    'camelCase 命名，如 "searchBar"\n'.gray +
    '> '
  )
  const isCreateRoute = await question('是否需要创建路由? 是/否  == y/n')

  if (/[-_]/.test(componentName)) {
    throw new Error('组件名称不合法，请使用 camelCase 命名')
  }
  // if (!/Service$/.test(serviceName)) {
  //   throw new Error('服务名称不合法，必须以Service结尾')
  // }

  console.log(c.gray(`正在创建 ${componentName}.ts ...`))

  let dir = path.join(__dirname, commonComponentDir, `${componentName}`)
  if (isCreateRoute === 'y' || isCreateRoute === '是') {
    dir = path.join(__dirname, componentDir, `${componentName}`)
  }
  fs.mkdirSync(dir)
  fs.writeFileSync(`${dir}/${componentName}.less`, `\
.wrapper {
  text-align: left;
}\n`)

  const name = componentName[0].toUpperCase() + componentName.slice(1)

  const isNeedForm = await question('是否是 export default 导出 y/n:')

  fs.writeFileSync((`${dir}/${componentName}.tsx`), `\
import { ReactComponentExt } from '@helpers/ReactExt'
import * as React from 'react'
import * as styles from './${componentName}.less'

console.log(styles)

// tslint:disable-next-line:no-empty-interface
export interface ${name}Props {

}

${isNeedForm !== 'y' ? 'export ' : ''}class ${name} extends ReactComponentExt<${name}Props, {}> {
  public init(): void {
    // todo
  }

  public componentDidMount() {
    // todo
  }

  public render() {
    return (
      <div className={styles.wrapper}>{}</div>
    )
  }

}

${isNeedForm === 'y' ? `export default ${name} ` : ''}
\n`)

  if (isCreateRoute === 'y' || isCreateRoute === '是') {
    if (isNeedForm === 'y') {
      await exec(`yarn run createRoute ${componentName}`)
    } else {
      await exec(`yarn run createRoute`)
    }

  }
  console.log(`完成`.green)
}

main().catch((err) => {
  console.error(c.red(err))
})